/**
 * 统计卡片组件
 * 用于显示各种统计数据，支持图标、趋势、进度条等
 */
class StatCard extends BaseComponent {
    constructor(options = {}) {
        super({
            ...options,
            className: `stat-card ${options.className || ''}`
        });

        // 组件配置
        this.title = options.title || '';
        this.value = options.value || '0';
        this.icon = options.icon || '';
        this.color = options.color || 'blue';
        this.trend = options.trend || null;
        this.description = options.description || '';
        this.progress = options.progress || null;
        this.onClick = options.onClick || null;

        // 颜色映射
        this.colorMap = {
            blue: {
                bg: 'bg-blue-100',
                text: 'text-blue-600',
                icon: 'text-blue-500',
                border: 'border-blue-500'
            },
            green: {
                bg: 'bg-green-100',
                text: 'text-green-600',
                icon: 'text-green-500',
                border: 'border-green-500'
            },
            yellow: {
                bg: 'bg-yellow-100',
                text: 'text-yellow-600',
                icon: 'text-yellow-500',
                border: 'border-yellow-500'
            },
            red: {
                bg: 'bg-red-100',
                text: 'text-red-600',
                icon: 'text-red-500',
                border: 'border-red-500'
            },
            purple: {
                bg: 'bg-purple-100',
                text: 'text-purple-600',
                icon: 'text-purple-500',
                border: 'border-purple-500'
            },
            indigo: {
                bg: 'bg-indigo-100',
                text: 'text-indigo-600',
                icon: 'text-indigo-500',
                border: 'border-indigo-500'
            },
            pink: {
                bg: 'bg-pink-100',
                text: 'text-pink-600',
                icon: 'text-pink-500',
                border: 'border-pink-500'
            },
            cyan: {
                bg: 'bg-cyan-100',
                text: 'text-cyan-600',
                icon: 'text-cyan-500',
                border: 'border-cyan-500'
            }
        };

        // 获取当前颜色配置
        this.colors = this.colorMap[this.color] || this.colorMap.blue;
    }

    /**
     * 渲染统计卡片
     */
    render() {
        const template = `
            <div class="stat-card-wrapper ${this.className}" data-component-id="${this.id}">
                <div class="bg-white rounded-lg border border-slate-200 p-6 hover:shadow-lg transition-all duration-300 hover:scale-[1.02]">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex-1">
                            <p class="text-sm font-medium text-slate-600 mb-1">${this.title}</p>
                            <p class="text-2xl font-bold text-slate-800 ${this.trend ? 'mb-2' : ''}">${this.formatValue(this.value)}</p>
                            ${this.renderTrend()}
                            ${this.renderDescription()}
                        </div>
                        <div class="w-12 h-12 ${this.colors.bg} rounded-lg flex items-center justify-center ${this.onClick ? 'cursor-pointer hover:scale-110 transition-transform' : ''}">
                            <i class="${this.icon} ${this.colors.icon} text-xl"></i>
                        </div>
                    </div>
                    ${this.renderProgress()}
                </div>
            </div>
        `;

        // 创建或更新元素
        if (!this.element) {
            this.element = this.createElementFromTemplate(template);
        } else {
            this.element.outerHTML = template;
            this.element = this.container.querySelector(`[data-component-id="${this.id}"]`);
        }

        // 绑定点击事件
        this.bindEvents();
    }

    /**
     * 格式化数值
     */
    formatValue(value) {
        if (typeof value === 'number') {
            // 大数字格式化
            if (value >= 1000000) {
                return (value / 1000000).toFixed(1) + 'M';
            } else if (value >= 1000) {
                return (value / 1000).toFixed(1) + 'K';
            } else if (value % 1 !== 0) {
                return value.toFixed(1);
            } else {
                return value.toLocaleString();
            }
        }
        return value;
    }

    /**
     * 渲染趋势指示器
     */
    renderTrend() {
        if (!this.trend) return '';

        const { value, type = 'percentage' } = this.trend;
        const isPositive = value > 0;
        const icon = isPositive ? 'fa-arrow-up' : 'fa-arrow-down';
        const color = isPositive ? 'text-green-600' : 'text-red-600';

        let displayValue = '';
        if (type === 'percentage') {
            displayValue = `${Math.abs(value)}%`;
        } else {
            displayValue = this.formatValue(Math.abs(value));
        }

        return `
            <div class="flex items-center space-x-1">
                <i class="fas ${icon} ${color} text-xs"></i>
                <span class="${color} text-sm font-medium">${displayValue}</span>
                <span class="text-slate-500 text-sm">较上月</span>
            </div>
        `;
    }

    /**
     * 渲染描述信息
     */
    renderDescription() {
        if (!this.description) return '';

        return `
            <p class="text-sm text-slate-500">${this.description}</p>
        `;
    }

    /**
     * 渲染进度条
     */
    renderProgress() {
        if (!this.progress) return '';

        const { value, max = 100, color = 'blue', showLabel = true } = this.progress;
        const percentage = Math.min((value / max) * 100, 100);
        const progressColor = this.colorMap[color] || this.colorMap.blue;

        return `
            <div class="space-y-2">
                ${showLabel ? `
                    <div class="flex justify-between text-sm">
                        <span class="text-slate-600">完成进度</span>
                        <span class="font-medium ${progressColor.text}">${percentage.toFixed(1)}%</span>
                    </div>
                ` : ''}
                <div class="w-full bg-slate-200 rounded-full h-2">
                    <div class="${progressColor.bg} h-2 rounded-full transition-all duration-500" style="width: ${percentage}%"></div>
                </div>
            </div>
        `;
    }

    /**
     * 从模板创建元素
     */
    createElementFromTemplate(template) {
        const div = document.createElement('div');
        div.innerHTML = template.trim();
        return div.firstElementChild;
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        if (!this.element) return;

        // 点击事件
        if (this.onClick) {
            const clickableElements = this.element.querySelectorAll('.hover\\:scale-110, .cursor-pointer');
            clickableElements.forEach(element => {
                element.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    this.onClick.call(this, this);
                });
            });
        }

        // 悬停效果
        const card = this.element.querySelector('.bg-white');
        if (card) {
            card.addEventListener('mouseenter', () => {
                this.emit('mouseenter');
            });

            card.addEventListener('mouseleave', () => {
                this.emit('mouseleave');
            });
        }
    }

    /**
     * 更新数据
     */
    updateData(newData) {
        const oldData = {
            title: this.title,
            value: this.value,
            trend: this.trend,
            description: this.description,
            progress: this.progress
        };

        // 更新属性
        Object.assign(this, newData);

        // 触发数据更新事件
        this.emit('dataUpdated', { oldData, newData: this });

        // 重新渲染
        this.render();

        return this;
    }

    /**
     * 设置数值
     */
    setValue(value) {
        this.value = value;
        this.render();
        return this;
    }

    /**
     * 设置趋势
     */
    setTrend(trend) {
        this.trend = trend;
        this.render();
        return this;
    }

    /**
     * 设置进度
     */
    setProgress(progress) {
        this.progress = progress;
        this.render();
        return this;
    }

    /**
     * 设置颜色
     */
    setColor(color) {
        this.color = color;
        this.colors = this.colorMap[color] || this.colorMap.blue;
        this.render();
        return this;
    }

    /**
     * 加载状态
     */
    setLoading(loading) {
        if (loading) {
            this.element?.classList.add('opacity-50', 'pointer-events-none');
            this.emit('loadingStart');
        } else {
            this.element?.classList.remove('opacity-50', 'pointer-events-none');
            this.emit('loadingEnd');
        }
        return this;
    }

    /**
     * 错误状态
     */
    setError(error) {
        this.element?.classList.add('border-red-200', 'bg-red-50');
        const errorElement = this.element?.querySelector('.text-slate-600');
        if (errorElement) {
            errorElement.textContent = error || '数据加载失败';
            errorElement.classList.add('text-red-600');
        }
        this.emit('error', { error });
        return this;
    }

    /**
     * 重置状态
     */
    reset() {
        this.element?.classList.remove('border-red-200', 'bg-red-50', 'opacity-50', 'pointer-events-none');
        this.render();
        return this;
    }
}

// 导出组件
window.StatCard = StatCard;